<?php namespace Common\Model;
use \Hdphp\Model\Model;
/*
 * 类别模型
 * */
 	class Category extends Model
 	{
 		protected $table = "category";//所要连接的表名
		//自动验证
		protected $validate = array(
		array("cname","required","类别名不能为空",3,3),
		
		);
		
		/*
		 * 验证添加
		 * */
		 public function add_cate()
		 {
		 	if(!$this->create()){
		 		return false;
		 	}
			//p($_POST["cname"]);
			$data = $this->where("cname",$_POST["cname"])->first();
			//p($data);
			if($data["cname"]==$_POST["cname"]){
				$this->error = "类别名已存在";
				return false;
			}
			return $this->add();
		 }
		 /*
		  * 验证编辑
		  * */
		  public function reset_cate($cid)
		  {
		  	//$cid=$_GET["cid"];
		  	if(!$this->create()){return false;}
			//p($cid);die;
			return $this->where("cid",$cid)->save();
		  }
		 /*
		  * 获得除去子集和自己的数据
		  * */
		  public function getCataData($cid)
		  {
		  	//获得子集
		  	$cids = $this->getSon($this->get(),$cid);
			//将自己追加到数组中
			$cids[] = $cid;
			//获得
			$cids = implode(",", $cids);
			$catedata = $this->where("cid not in ($cids)")->get();
			//p($catedata);
			return Data::tree($catedata,"cname");
		  }
		 /*
		  * 获得子集
		  * */
		  public function getSon($data,$cid)
		  {
		  	static $arr = array();
		  	foreach($data as $k=>$v)
			{
				if($cid==$v["pid"]){
					$arr[] = $v["cid"];
					$this->getSon($data,$v["cid"]);
				}
			}
			return $arr;
		  }
		  /*
		   * 删除方法
		   * */
		   public function del($cid)
		   {
		   	//将别删除项的子集向上提一级
		   	//1.获得将要删除的父类
		   	$par_data = $this->where("cid",$cid)->pluck("pid");
			//p($par_data);die;
		   	$data = $this->where("pid",$cid)->update(array("pid"=>$par_data));
			//p($data);die;
		   	//执行删除
		   	 return $this->where("cid",$cid)->delete();
		   }
		  
 	}
